import React, { useState, useEffect } from 'react';
import { Button, Badge, message } from 'antd';
import { MessageOutlined, CloseOutlined } from '@ant-design/icons';
import ChatPanel from './ChatPanel';
import ragService from '../../services/rag';
import './AIChatWidget.css';

const AIChatWidget = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [threads, setThreads] = useState([]);
  const [currentThread, setCurrentThread] = useState(null);
  const [unreadCount, setUnreadCount] = useState(0);
  const [loading, setLoading] = useState(false);

  // 组件挂载时获取线程列表
  useEffect(() => {
    loadThreads();
  }, []);

  // 添加调试信息
  useEffect(() => {
  }, [threads, currentThread, isOpen]);

  // 加载线程列表
  const loadThreads = async () => {
    try {
      setLoading(true);
      const response = await ragService.getThreads(1, 20);
      
      if (response.data.code === 200) {
        const threadList = response.data.data.list || [];
        setThreads(threadList);
        
        // 如果有线程，默认选择最近使用的
        if (threadList.length > 0 && !currentThread) {
          setCurrentThread(threadList[0]);
        }
      } else {
        message.error(response.data.message || '获取对话列表失败');
      }
    } catch (error) {
      message.error('加载对话列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 创建新线程
  const createNewThread = async (name = '') => {
    try {
      const response = await ragService.createThread(name);
      
      if (response.data.code === 200) {
        const newThread = response.data.data;
        
        // 将新线程添加到列表开头
        setThreads(prev => {
          const updatedThreads = [newThread, ...prev];
          return updatedThreads;
        });
        
        // 设置为当前线程
        setCurrentThread(newThread);
        
        return newThread;
      } else {
        throw new Error(response.data.message || '创建失败');
      }
    } catch (error) {
      message.error(`创建新对话失败: ${error.message || error}`);
      throw error;
    }
  };

  // 删除线程
  const deleteThread = async (threadId) => {
    try {
      if (!threadId) {
        throw new Error('线程ID不能为空');
      }
      
      const response = await ragService.deleteThread(threadId);
      
      // 检查删除是否成功 - 根据API文档检查success字段
      if (response.data.success === true || response.data.code === 200) {
        // 更新线程列表
        const updatedThreads = threads.filter(t => t.threadId !== threadId);
        setThreads(updatedThreads);
        
        // 如果删除的是当前线程，切换到其他线程
        if (currentThread?.threadId === threadId) {
          const newCurrentThread = updatedThreads.length > 0 ? updatedThreads[0] : null;
          setCurrentThread(newCurrentThread);
        }
        
        return Promise.resolve();
      } else {
        throw new Error(response.data.message || '删除失败');
      }
    } catch (error) {
      const errorMessage = error.response?.data?.message || error.message || '删除对话失败';
      message.error(errorMessage);
      throw error;
    }
  };

  // 切换聊天面板显示状态
  const toggleChat = () => {
    setIsOpen(!isOpen);
    if (!isOpen) {
      setUnreadCount(0); // 打开时清除未读计数
    }
  };

  // 处理新消息（可以用于未来的实时通知）
  const handleNewMessage = () => {
    if (!isOpen) {
      setUnreadCount(prev => prev + 1);
    }
  };

  // 处理线程变化
  const handleThreadChange = (thread) => {
    setCurrentThread(thread);
  };

  // 关闭聊天面板
  const handleCloseChat = () => {
    setIsOpen(false);
  };

  return (
    <div className="ai-chat-widget">
      {/* 聊天面板 */}
      {isOpen && (
        <ChatPanel
          threads={threads}
          currentThread={currentThread}
          onThreadChange={handleThreadChange}
          onCreateThread={createNewThread}
          onDeleteThread={deleteThread}
          onRefreshThreads={loadThreads}
          onClose={handleCloseChat}
          loading={loading}
        />
      )}

      {/* 悬浮按钮 */}
      <div className="ai-chat-button">
        <Badge count={unreadCount} size="small">
          <Button
            type="primary"
            shape="circle"
            size="large"
            icon={isOpen ? <CloseOutlined /> : <MessageOutlined />}
            onClick={toggleChat}
            className={`chat-toggle-btn ${isOpen ? 'active' : ''}`}
          />
        </Badge>
      </div>
    </div>
  );
};

export default AIChatWidget;